import { defineComponent, ExtractPropTypes, getCurrentInstance, inject, onBeforeUnmount, PropType, computed } from 'vue'
import { remove } from '@vue/shared'
import { computedEager } from '@vueuse/core'
import DisplayDirective, { DisplayDirectiveType } from '../_internal/display-directive'
import { TabsContextKey } from './interface'
import { getKey } from './utils'

const preCls = 'x-tab-pane'

const tabPaneProps = {
  label: [String, Number],
  name: [String, Number],
  displayDirective: String as PropType<DisplayDirectiveType>
}

export type TabPaneProps = ExtractPropTypes<typeof tabPaneProps>

export default defineComponent({
  name: preCls,
  props: tabPaneProps,
  setup(props, { slots }) {
    const proxy = getCurrentInstance()!.proxy!

    const tabsContext = inject(TabsContextKey)!

    tabsContext.tabpanes.value.push(proxy)
    onBeforeUnmount(() => remove(tabsContext.tabpanes.value, proxy))

    const key = computed(() => getKey(proxy) ?? tabsContext.tabpanes.value.indexOf(proxy))
    const visible = computedEager(() => key.value == tabsContext.value.value)


    return () => (
      <DisplayDirective type={props.displayDirective} visible={visible.value && !!slots.default}>
        <div class={preCls}>{slots.default?.()}</div>
      </DisplayDirective>
    )
  }
})
